package cn.qiguai.sphapi.interceptor;

import cn.qiguai.sphapi.controller.response.UserInfo;
import cn.qiguai.sphapi.exception.BusinessException;
import cn.qiguai.sphapi.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

public class JWTInterceptor implements HandlerInterceptor {
	private ObjectMapper objectMapper = new ObjectMapper();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//获取用户信息所在的cookie
		Cookie[] cookies = request.getCookies();
		String name = null;
		String userInfoStr = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				name = cookie.getName();
				if ("userInfo".equals(name)) {
					userInfoStr = cookie.getValue();
					break;
				}
			}
		}

		UserInfo userInfo = null;
		if (userInfoStr != null) {
			//解码并将将用户信息json转化为对象
			userInfoStr = URLDecoder.decode(userInfoStr, "UTF-8");
			userInfo = objectMapper.readValue(userInfoStr, UserInfo.class);
		} else {
			userInfo = new UserInfo();
		}

		if (!JWTUtils.verify(userInfo.getToken())) { //token不合法
			throw new BusinessException("您还未登录，暂无权限访问！");
		}

		return true;
	}
}
